package com.demo.spark.rdd;

import com.google.common.collect.Lists;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.rdd.RDD;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

public class RddCartesian {
    public static void main(String[] args) {
        SparkConf sparkConf = new SparkConf().setAppName("rdd cartesian").setMaster("local");
        JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
        sparkContext.setLogLevel("error");
        List<Integer> integers = Arrays.asList(1, 4, 6, 8);
        JavaRDD<Integer> parallelize = sparkContext.parallelize(integers,2);
        JavaPairRDD<Integer, Integer> cartesian = parallelize.cartesian(parallelize);
        List<Tuple2<Integer, Integer>> collect = cartesian.collect();
        for (Tuple2<Integer, Integer> integerIntegerTuple2 : collect) {
            System.out.println(integerIntegerTuple2._1+","+integerIntegerTuple2._2);
        }
        System.out.println("---");
        JavaPairRDD<Integer, Integer> integerIntegerJavaPairRDD = cartesian.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {

                return v1 * v2;
            }
        });
        List<Tuple2<Integer, Integer>> collect1 = integerIntegerJavaPairRDD.collect();
        for (Tuple2<Integer, Integer> integerIntegerTuple2 : collect1) {
            System.out.println(integerIntegerTuple2._1+","+integerIntegerTuple2._2);
        }
    }
}
